package
{
	import com.lib.playbook.dialog.DialogBase;
	
	import flash.display.Sprite;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.Socket;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.ByteArray;
	
	import qnx.events.QNXApplicationEvent;
	import qnx.system.QNXApplication;
	import qnx.ui.buttons.Button;
	import qnx.ui.buttons.LabelButton;
	
	[SWF(width="1024", height="600", backgroundColor="#cccccc", frameRate="30")]
	public class MyTest extends Sprite
	{
		private var _ground:Sprite;
		private var _menu:MenuBar;
		private var _socket:Socket;
		private var _channel:ChannelView;
		private var _shared_data:SharedData = SharedData.instance;
		public function MyTest()
		{
			QNXApplication.qnxApplication.addEventListener(QNXApplicationEvent.SWIPE_DOWN, showAppMenu);
			var helloButton:LabelButton = new LabelButton();
			helloButton.label = "Hello World!";
			helloButton.x = (stage.stageWidth - helloButton.width)/2;
			helloButton.y = (stage.stageHeight - helloButton.height)/2;
			
			var myFormat:TextFormat = new TextFormat();
			myFormat.color = 0xAA0000;
			myFormat.size = 24;
			myFormat.italic = true;
			myFormat.align = "center";
			var text:TextField = new TextField();
			text.text = "Connect";
			text.setTextFormat(myFormat);
			
			var closeButton:Button = new Button();
			closeButton.addChild(text);
			closeButton.addEventListener(MouseEvent.CLICK, connect);
			closeButton.x = (stage.stageWidth - closeButton.width)/2;
			closeButton.y = helloButton.y - helloButton.height;
			
			//addChild(helloButton);
			addChild(closeButton);
			_channel = new ChannelView();
			addChild(_channel);
			
			stage.nativeWindow.visible = true;
			_menu = new MenuBar();
	
			_ground = new Sprite();
			_ground.graphics.beginFill(0x5CACEE,1.0);
			_ground.graphics.drawRect(0,0,1024,600);
			_ground.graphics.endFill();
			_ground.alpha = 0.3;
			this.addChild(_ground);
			addChild(_menu);
			_ground.visible = false;
			
			DialogBase.showOn = this.stage;
			
			_shared_data.addEventListener(MouseEvent.MOUSE_DOWN, groundClick);
		}
		private function showAppMenu(event:QNXApplicationEvent):void
		{
			if(! _menu.isVisible())
			{
				_menu.show();
				_ground.visible = true;
				_ground.addEventListener(MouseEvent.MOUSE_DOWN, groundClick);
			}
		}
		private function groundClick(event:MouseEvent):void
		{
			if(_menu.isVisible())
			{
				_menu.processEvent(event);
				
			} 
			
			if(!_menu.isVisible()){
				_ground.visible = false;
				_ground.removeEventListener(MouseEvent.MOUSE_DOWN, groundClick);
			}
		}
		private function closeWindow(event:MouseEvent):void{
			stage.nativeWindow.close();
		}
		
		public function connect(host:String,port:int=6667,password:String=null):void
		{

			
			_socket = new Socket();
			
			// Initialise listeners
			_socket.addEventListener( "connect" , connectEvent , false , 0 );				
			_socket.addEventListener( "close" , closeEvent , false, 0 );
			_socket.addEventListener( "ioError" , ioErrorEvent , false, 0 );
			_socket.addEventListener( "securityError" , securityErrorEvent , false, 0 );
			_socket.addEventListener( "socketData" , socketDataEvent , false , 0 );
			// Connect to the server.
			//_socket.connect("chat.freenode.net",6667);
			var server:String = "irc.unrealircd.com";
			_socket.connect(server,6667);
		}
		public function sendRawLine(line:String):void
		{
			var cookedLine:ByteArray = new ByteArray();
			cookedLine.writeUTFBytes(line + "\r\n");
			// Write ByteArray to socket
			_socket.writeBytes(cookedLine);
			// Flushes any accumulated data in the socket's output buffer and sends it to the server
			_socket.flush();
		}
		private function connectEvent(event:Event):void
		{
			this.log("*** Connected to server. ***");
			sendRawLine("NICK " + "kaka3033");
			log("NICK " + "kaka3033");
			sendRawLine("USER " + "asircbot" + " 8 * :" + "0.1");
			log("USER " + "asircbot" + " 8 * :" + "0.1");
			
		}
		private function closeEvent(event:Event):void
		{
			this.log("The connection was closed."  + event.toString());
			//onDisconnect();
		}
		private function ioErrorEvent(event:Event):void
		{
			this.log("An IO error occurred"  + event.toString());
			throw new IOError(event.toString());
		}
		private function securityErrorEvent(event:Event):void
		{
			this.log("A Security error occurred"  + event.toString());
			throw new SecurityError(event.toString());
		}
		private function socketDataEvent(event:Event):void
		{

				//this.log("Verifying connection");
				//verifyConnection(event);
				//return;

			// Check to see if the socket has bytes in the stream

			var moreLines:Boolean = true;
			// keep handling lines while we have them to read.
			while (moreLines)
			{
				var line:String = this.readLine();
				if (line == null)
					moreLines = false;
				else
					this.handleLine(line);
			}

		}
		private function handleLine(line:String):void
		{
			if(line.indexOf("004")>=0){
				this.log("Connected!");
			}
			if(line.toLocaleLowerCase() == "ping"){
				this.sendRawLine("PONG");
			}
			_channel.appendHTML(line);
		}
		private var _readBuffer:String = "";
		protected function readLine():String
		{
			var readBytes:String;
			while (_socket.bytesAvailable)
			{
				readBytes = _socket.readUTFBytes(_socket.bytesAvailable);
				_readBuffer = _readBuffer.concat(readBytes);
			}
			var ret:String;
			var idx:int = _readBuffer.indexOf("\r\n");
			// check if we have a complete line in our read buffer.
			if (idx > -1)
			{
				// read the new line from the buffer
				ret = _readBuffer.substr(0,idx+2);
				// now remove this line from the buffer
				_readBuffer = _readBuffer.slice(idx+2);
				// return line minux the newline.
				return ret.replace("\r\n","");
			}
			return null;
		}
		public   function log(line:String):void
		{
			_channel.appendHTML(line + "<br>");
		}
	}
}